const WebSocket = require('ws');
const wss = new WebSocket.Server({port: 8010});
const code2ws = new Map();

wss.on('connection', function connection(ws, request) {
    ws.sendData = (event, data, fromCode) => {
        console.log('【发送数据】====>', JSON.stringify({event, data, fromCode}))
        ws.send(JSON.stringify({event, data, fromCode}));
    };
    ws.sendError = msg => {
        ws.sendData('error', {msg});
    };

    let code = Math.floor(Math.random() * (999999 - 100000)) + 100000;
    let ip = request.connection.remoteAddress.replace('::ffff:', '');


    console.log('【有设备连接】====>IP:', ip, " PORT:", request.connection.remotePort);

    code2ws.set(code, ws);

    ws.on('message', function incoming(message) {
        let parsedMessage = {};
        try {
            parsedMessage = JSON.parse(message);
        } catch (e) {
            ws.sendError('message not valid');
            return;
        }


        // let { event, data } = parsedMessage;
        let event = parsedMessage.event
        let remoteCode = parsedMessage.remoteCode
        let data = parsedMessage.data
        switch (event) {
            case 'login':
                console.log('【收到登录请求】====>', parsedMessage);
                handleLogin(ws, code);
                break;
            case 'logout':
                console.log('【收到断开连接请求】====>', parsedMessage);
                handleLogout(ws, code);
                break;
            case 'control':
                console.log('【收到控制请求】====>', parsedMessage);
                handleControl(ws, data, remoteCode);
                break;
            case 'forward':
                console.log('【收到转发请求】====>', parsedMessage);
                handleForward(ws, data, remoteCode);
                break;

            default:
                console.log('【收到未知请求】====>', parsedMessage);
                handleUnknown(ws, message);
                break;
        }
    });

    ws.on('close', () => {
        code2ws.delete(code);
        delete ws.sendRemote;
        clearTimeout(ws._closeTimeout);
    });

    ws._closeTimeout = setTimeout(() => {
        ws.terminate();
    }, 600000);
});

// 处理登录
function handleLogin(ws, code) {
    console.log('【返回登录数据】====>', code)
    ws.sendData('logined', {code});
}

function handleLogout(ws, code) {
    console.log('【返回断开连接数据】====>', code)
    ws.sendData('logouted', {code});
    ws.terminate();
}





// 处理设备发起控制另外一台设备请求
function handleControl(ws, data, remoteCode) {
    let code = +remoteCode;
    data = data || {}; // 如果 data 为 undefined 或 null，则初始化为空对象
    data.data = data.data || ""; // 处理 data.data 的空值
    if (code2ws.has(code)) {
        ws.sendData('controlled', {remoteCode: code}); // 告诉发起控制请求的设备，已经收到控制请求
        let remoteWS = code2ws.get(code); // 获取远程ws
        remoteWS.sendData('be-controlled', data.data,  getFromCode(ws));
    }
}


function handleForward(ws, data, remoteCode) {
    let code = +remoteCode;
    data = data || {}; // 如果 data 为 undefined 或 null，则初始化为空对象
    data.data = data.data || ""; // 处理 data.data 的空值

    if (code2ws.has(code)) {
        let remoteWS = code2ws.get(code);
        remoteWS.sendData(data.event, data, getFromCode(ws));
    }
}

function handleUnknown(ws, message) {

}

function getFromCode(ws) {
    for (const [key, val] of code2ws.entries()) {
        if (val === ws) {
            return key
        }
    }
}